package org.winexpress
import grails.converters.JSON
import org.codehaus.groovy.grails.web.json.JSONObject
import org.codehaus.groovy.grails.web.json.JSONArray
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
class PaymentController {

    def payment =
    {
        //get total price by user name 
        if (params['userid'].equals("") == false)
        {
             session.customerUsername = params['userid']
        }
        //session.customerUsername = 'fgb'
         def username =session.customerUsername 
         def txt = new URL("http://localhost:8080/WineXpress/totalprice?username=" + username).text
         JSONObject o = new JSONObject(txt)
         def pay = o.get("totalprice")
         def products = o.get("products")
         
        
         [pay:pay, products:products]
    }
    def pay =
    {
        def price =params['price']
        def address = params['address']
        def deliveryDate = params['dobYear'] + '-' + params['dobMonth'] + "-" + params['dobDay']
        def products = params['product']
        def strUsername = "WineXp_1334141863_biz_api1.comp.nus.edu.sg"
        def strPassword = "1334141888"
        def strSignature = "A.sb9TOACuCwLENm4d7B.s01gldKAt-SB3J8QzhRaHCTxKwkk7rVjQpY"
        def strAPIVersion = "65.1"
        def strCredentials = "USER=" + strUsername + "&PWD=" + strPassword + "&SIGNATURE=" + strSignature+"&VERSION="+strAPIVersion         
        def strNVPSandboxServer = "https://api-3t.sandbox.paypal.com/nvp";       
        def url ='http://localhost:8088/WineXpressClient/'
        //session.customerUsername ='fgb'
        def user = session.customerUsername +","+price + address +"_"+ deliveryDate
        def successUrl =url + 'success?userid='+user              
        def cancelUrl = url+'payment/?userid='+session.customerUsername        
        def strNVP = strCredentials + "&METHOD=SetExpressCheckout&RETURNURL="+successUrl+"&CANCELURL="+cancelUrl
        strNVP = strNVP+"&PAYMENTREQUEST_0_PAYMENTACTION=SALE&PAYMENTREQUEST_0_CURRENCYCODE=SGD&PAYMENTREQUEST_0_AMT="+price         
        strNVP = strNVP+"&L_PAYMENTREQUEST_0_ITEMCATEGORY0=Physical"        
        def list = products.split(';')
        def items =""
        
        def i =0
        list.each(){

            def itea = it.split(',')
 

            //println itea[1]
        if (i==0)
            {
                items = "&L_PAYMENTREQUEST_0_NAME"+i +"="+itea[0] + "&L_PAYMENTREQUEST_0_QTY"+ i +"="+ itea[2] +"&L_PAYMENTREQUEST_0_AMT" +i+"="+itea[1]
            }
            else
            {
                items = items +"&L_PAYMENTREQUEST_0_NAME"+i +"="+itea[0] + "&L_PAYMENTREQUEST_0_QTY"+ i +"="+ itea[2] +"&L_PAYMENTREQUEST_0_AMT" +i+"="+itea[1]
            }
            i=i+1
        }

        strNVP = strNVP+items
        
                HttpClient httpclient = new DefaultHttpClient()
        HttpResponse response
        HttpPost httppost = new HttpPost(strNVPSandboxServer)
        StringEntity se = new StringEntity(strNVP)          
        httppost.setEntity(se);          
        response = httpclient.execute(httppost);
        if (response != null) {            
            HttpEntity r_entity = response.getEntity()
            String res = EntityUtils.toString(r_entity)
            println res
            def arr  = res.split("=")
            arr = arr[1].split('&')
            def token = "EC-" + arr[0].toString().substring(5)
            def checkoutUrl = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + token
            redirect(url:checkoutUrl)
        }
    }
    
    def success = 
    {
                def token = params.token
        Map map = [:]        
      

        def strUsername = "WineXp_1334141863_biz_api1.comp.nus.edu.sg"
        def strPassword = "1334141888"
        def strSignature = "A.sb9TOACuCwLENm4d7B.s01gldKAt-SB3J8QzhRaHCTxKwkk7rVjQpY"
        def strCredentials = "USER=" + strUsername + "&PWD=" + strPassword + "&SIGNATURE=" + strSignature
        def strNVPSandboxServer = "https://api-3t.sandbox.paypal.com/nvp";
        def strAPIVersion = "56.0";
        def strNVP = strCredentials + "&METHOD=GetExpressCheckoutDetails&TOKEN="+token+"&VERSION=" + strAPIVersion
        HttpClient httpclient = new DefaultHttpClient()
        HttpResponse response
        HttpPost httppost = new HttpPost(strNVPSandboxServer)
        StringEntity se = new StringEntity(strNVP)        
        httppost.setEntity(se);          
        response = httpclient.execute(httppost);
        if (response != null) {
            HttpEntity r_entity = response.getEntity()
            String res = EntityUtils.toString(r_entity)
            def arr = res.split("&")
            println res 
            String ack = arr[3].substring(4)
            if (ack == "Success")
            {
                token = arr[0].toString().substring(6)
                def payeeID = arr[7].toString().substring(8)                
                def userid = params.userid                 
                def args = userid.split(',')
                userid = args[0].toString()
                def address = args[1]
               
                def amount = arr[21].toString().replaceAll("%2e",".")
                amount = amount.substring(4)
                //println amount
                strNVP = strCredentials+"&METHOD=DoExpressCheckoutPayment&=PAYMENTREQUEST_0_PAYMENTACTION=Authorization&TOKEN="+token+"&PAYERID="+payeeID+"&PAYMENTREQUEST_0_CURRENCYCODE=SGD&PAYMENTREQUEST_0_AMT="+amount + "&VERSION=" + 65.1
                httpclient = new DefaultHttpClient()
                httppost = new HttpPost(strNVPSandboxServer)
                se = new StringEntity(strNVP)        
                httppost.setEntity(se);          
                response = httpclient.execute(httppost);
                if (response != null) {
                    r_entity = response.getEntity()
                    res = EntityUtils.toString(r_entity)
                    def arrs =res.split("&")
                    ack= arrs[4].toString().substring(4)
                    if (ack=="Success")
                    {
                        def txt = new URL("http://localhost:8080/WineXpress/success?username=" + userid+"&address="+address+"&amt="+amount).text                    
         JSONObject o = new JSONObject(txt)
         def status = o.get("status")
         if (status.equals("ok"))

                        redirect(url:"http://localhost:8088/WineXpressClient/thank")
                        
                    }}}}
    }
   def thank=
   {
       
   }
}
